﻿/*
rmenu jQuery plugin
=====================

Version: 1.0

Requisites: jQuery, cssmenu

Features: Create a css menu

Usage:
- Define a menu structure in an object
    var menu = {
        file: {
            caption: 'File',
            items: {
                new: {
                    caption: 'New',
                    click: function() {...}
                },
                ...
            },
        edit: {
            ...
        }
    }
- Call `rmenu` method on the target element
*/
$.fn.rmenu = function (menu) {
    function hide(element) {
        var ul = $(element).closest('.rmenu ul ul');
        ul.addClass('hidden');
        window.setTimeout(function () {
            ul.removeClass('hidden');
        }, 200);
    }

    menu.click = function (item, e) {
        var names = $(e.target).closest('a').attr('target').split(',');
        hide(e.target);

        var targets = [];
        var cur = menu;
        for (var i = 0; i < names.length; i++) {
            targets.push(cur[names[i]]);
            cur = cur[names[i]].items;
        }
        var item = targets[targets.length - 1];
        var root = targets[0];
        if (item.click) {
            item.click(item.item, root.item);
        }
        else {
            alert(item.caption);
        }
        //e.stopPropagation();
    };

    new RMenu(this, menu, []);
}

function RMenu(element, menu, target) {
    var ul = $('<ul>').appendTo(element);
    for (var key in menu) {
        var mode = menu[key].mode;
        if (mode == 'client' && !Services.localSupport) {
            continue;
        }
        else if (mode == 'server' && Services.localSupport) {
            continue;
        }

        if (menu[key].caption == '-') {
            $('<hr>').appendTo(ul);
        }
        else {
            var newTarget = target.slice(0)
            newTarget.push(key);

            var li = $('<li>').appendTo(ul);
            menu[key].item = li;
            var a = $('<a>').appendTo(li).append($('<span>').text(menu[key].caption)).attr({
                href: 'javascript:;',
                target: newTarget.toString()
            });
            if (menu[key].click) {
                a.attr('data-bind', 'click: click');
            }
            if (menu[key].items) {
                new RMenu(li, menu[key].items, newTarget);
            }
        }
    }
}